package com.share.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class Client {
	
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		
		//client端不用bossGroup
		NioEventLoopGroup workerGroup = new NioEventLoopGroup();
		
		try {
			Bootstrap b = new Bootstrap();
			b.group(workerGroup);
			b.channel(NioSocketChannel.class);
			b.option(ChannelOption.SO_KEEPALIVE, true);
			b.handler(new ChannelInitializer<SocketChannel>() {

				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new ClientHandler());
				}
			});
			
			ChannelFuture f = b.connect("127.0.0.1", 12345).sync();
			
			/*
			 * ChannelFuture代表了一个还没有发生的IO操作
			 * 这意味着一个请求不会马上执行，因为netty中所有的操作都是异步的
			 */
			ChannelFuture writeAndFlush = f.channel().writeAndFlush(Unpooled.copiedBuffer("777".getBytes()));
			System.out.println("client  发送：  777" );
			
			//等待直到connet被关闭
			f.channel().closeFuture().sync();
			
		} catch (Exception e) {
			System.out.println(e);
		} finally {
			workerGroup.shutdownGracefully();
		}
	}

}
